<?php

namespace App\Repositories;



use App\Interfaces\UserViewHistoryService;
use App\Models\UserViewHistory;
use App\Models\Goods;
use DB;

class UserViewHistoryRepository implements UserViewHistoryService{

    protected $user_id;

    protected $session_id;

    public function __construct($user_id,$session_id){

        $this->user_id = $user_id;

        $this->session_id = $session_id;

    }

    public function add($goods_id){

        $goods = Goods::find($goods_id);

        if (!$goods) return false;

       $exists = UserViewHistory::where('goods_id',$goods_id)

           ->where(function($query) {
               $query->where('user_id',$this->user_id)
               ->orWhere('session_id',$this->session_id);
           })->first();

        if ($exists){

            $exists->view_time = date('Y-m-d H:i:s');
            $exists->save();

            return $exists;

        }else{
            return UserViewHistory::create([
                'user_id'=>$this->user_id,
                'session_id'=>$this->session_id,
                'goods_id'=>$goods_id,
                'view_time'=>date('Y-m-d H:i:s')
            ]);

        }

    }

    public function getByDayGroupPaginate(){


        return UserViewHistory::join('goods','user_view_history.goods_id','=','goods.goods_id')
            ->where('user_view_history.user_id',$this->user_id)
            ->whereNull('goods.deleted_at')
            ->orderBy('view_time', 'desc')
            ->paginate(20);
    }
}